前端使用 jest 做单元测试

1. 安装 Jest

1
npm install --save-dev jest

2. 在script里面加上下面一句:

1
2
3
4
5
6
/ 添加测试命令
{
"scripts": {
"test": "jest"
}
}

3. 添加被测试文件

1
2
3
4
5
// 被测试文件 sum.js
function sum(a, b) {
return a + b;
}
module.exports = sum;

4. 书写测试文件

1
2
3
4
5
// 测试文件 sum.test.js
const sum = require(‘./sum');
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});

5. 控制台执行

1
2
3
npm test
// 或者
npm t

vue+typescript+jest测试指南